package pt.ipl.isel.deetc.leic.pdm.g12.yamba;

import android.app.IntentService;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;

public class StatusUploadService extends IntentService {
	public static final String ARG_KEY = "arg";
	public static final String ARG_ACTION = "action";    
	
	public StatusUploadService() {	
		super("StatusUploadService");	
	}
	
	@Override
	protected void onHandleIntent(Intent intent) {		
		action(intent);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}
	
	private void action(Intent intent) {		
		YambaPdmApp yamba = (YambaPdmApp) getApplication(); 		
		String action = intent.getStringExtra(ARG_ACTION);
		
		try {			
			if(action.equals("post")) {				
				yamba.getTwitter().updateStatus(intent.getStringExtra(ARG_KEY));
			}
			if(action.equals("postOffline")) {	
				int id;
				Cursor cursor = getContentResolver().query(StatusToPostContract.CONTENT_URI, null, null, null, null);
				if(cursor.moveToFirst()) {
					do {
						id = cursor.getInt(0);
						yamba.getTwitter().updateStatus(cursor.getString(1));
						getContentResolver().delete(Uri.withAppendedPath(StatusToPostContract.CONTENT_URI,""+id), null, null);
			    	} while (cursor.moveToNext());
				}
				cursor.close();
			}
		}
		catch (RuntimeException e) {
			if(action.equals("post")) {
				ContentValues values = new ContentValues();
				values.put(StatusToPostContract.STATUS, intent.getStringExtra(ARG_KEY));				
				getContentResolver().insert(StatusToPostContract.CONTENT_URI, values);
			}
		}
	}
}
